<template>
  <div class="inventory-status-report">
    <!-- 搜索过滤区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="商品分类">
          <el-select v-model="filterForm.categoryId" placeholder="选择分类" clearable>
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="filterForm.warehouseId" placeholder="选择仓库" clearable>
            <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option v-for="(name, value) in stockStatus" :key="value" :label="name" :value="Number(value)" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 库存状态概览卡片 -->
    <div class="summary-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-item">
              <div class="summary-icon normal-icon">
                <el-icon><Goods /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">总库存商品</div>
                <div class="summary-value">{{ totalProducts }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-item">
              <div class="summary-icon warning-icon">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">库存预警</div>
                <div class="summary-value">{{ warningCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-item">
              <div class="summary-icon danger-icon">
                <el-icon><Remove /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">缺货商品</div>
                <div class="summary-value">{{ outOfStockCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-item">
              <div class="summary-icon info-icon">
                <el-icon><TopRight /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">超储商品</div>
                <div class="summary-value">{{ overStockCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 库存状态表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px;"
      v-loading="loading"
      :default-sort="{ prop: 'stockQuantity', order: 'descending' }"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="id" label="ID" width="80" sortable />
      <el-table-column prop="name" label="商品名称" min-width="200" sortable show-overflow-tooltip class-name="text-left" />
      <el-table-column prop="sku" label="SKU" width="120" sortable show-overflow-tooltip class-name="text-left" />
      <el-table-column label="分类" width="120" sortable="custom" prop="categoryId">
        <template #default="scope">
          {{ scope.row.category ? scope.row.category.name : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="stockQuantity" label="库存数量" width="120" sortable>
        <template #default="scope">
          <span>{{ scope.row.stockQuantity || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="stockUnit" label="单位" width="80" />
      <el-table-column label="库存状态" width="100" sortable="custom" prop="stockStatus">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.stockStatus)" size="small">
            {{ getStatusText(scope.row.stockStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预警阈值" width="180">
        <template #default="scope">
          <div>
            最低: <span class="threshold">{{ scope.row.minimumStock || '-' }}</span>
          </div>
          <div>
            最高: <span class="threshold">{{ scope.row.maximumStock || '-' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="costPrice" label="成本价" width="100" sortable>
        <template #default="scope">
          <span>{{ formatPrice(scope.row.costPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="goToProductDetail(scope.row.id)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, inject } from 'vue';
import { useRouter } from 'vue-router';
import { getInventoryStatusReport } from '@/api/inventory';
import { getAllCategories } from '@/api/category';
import { getAllWarehouses } from '@/api/inventory';
import { formatPrice } from '@/utils/format';

export default {
  name: 'InventoryStatusReport',
  emits: ['loading-change'],
  setup(props, { emit }) {
    const router = useRouter();
    const loading = inject('loading', ref(false));
    
    // 过滤条件
    const filterForm = reactive({
      categoryId: null,
      warehouseId: null,
      status: null,
      sortBy: 'stockQuantity',
      sortOrder: 'desc'
    });
    
    // 表格数据
    const tableData = ref([]);
    const categories = ref([]);
    const warehouses = ref([]);
    
    // 库存状态映射
    const stockStatus = {
      0: '缺货',
      1: '正常',
      2: '预警',
      3: '超储'
    };
    
    // 统计数据
    const totalProducts = computed(() => tableData.value.length);
    
    const warningCount = computed(() => {
      return tableData.value.filter(item => item.stockStatus === 2).length;
    });
    
    const outOfStockCount = computed(() => {
      return tableData.value.filter(item => item.stockStatus === 0).length;
    });
    
    const overStockCount = computed(() => {
      return tableData.value.filter(item => item.stockStatus === 3).length;
    });
    
    // 获取库存状态标签类型
    const getStatusType = (status) => {
      const map = {
        0: 'danger',  // 缺货
        1: 'success', // 正常
        2: 'warning', // 预警
        3: 'info'     // 超储
      };
      return map[status] || '';
    };
    
    // 获取库存状态文本
    const getStatusText = (status) => {
      return stockStatus[status] || '未知';
    };
    
    // 获取库存状态报表数据
    const fetchData = async () => {
      emit('loading-change', true);
      try {
        // 构建查询参数
        const params = { ...filterForm };
        
        const response = await getInventoryStatusReport(params);
        tableData.value = response.data || [];
      } catch (error) {
        console.error('获取库存状态报表失败:', error);
      } finally {
        emit('loading-change', false);
      }
    };
    
    // 加载基础数据
    const loadBaseData = async () => {
      try {
        const [categoriesRes, warehousesRes] = await Promise.all([
          getAllCategories(),
          getAllWarehouses()
        ]);
        
        categories.value = categoriesRes.data || [];
        warehouses.value = warehousesRes.data || [];
      } catch (error) {
        console.error('加载基础数据失败:', error);
      }
    };
    
    // 查询按钮事件处理
    const handleSearch = () => {
      fetchData();
    };
    
    // 重置按钮事件处理
    const handleReset = () => {
      Object.keys(filterForm).forEach(key => {
        if (key !== 'sortBy' && key !== 'sortOrder') {
          filterForm[key] = null;
        }
      });
      fetchData();
    };
    
    // 表格排序变化事件处理
    const handleSortChange = ({ prop, order }) => {
      if (prop) {
        filterForm.sortBy = prop;
        filterForm.sortOrder = order === 'ascending' ? 'asc' : 'desc';
        fetchData();
      }
    };
    
    // 跳转到商品详情
    const goToProductDetail = (id) => {
      router.push(`/admin/inventory/product/${id}`);
    };
    
    // 获取导出参数
    const getExportParams = () => {
      return { ...filterForm };
    };
    
    onMounted(() => {
      loadBaseData();
      fetchData();
    });
    
    return {
      loading,
      filterForm,
      tableData,
      categories,
      warehouses,
      stockStatus,
      totalProducts,
      warningCount,
      outOfStockCount,
      overStockCount,
      getStatusType,
      getStatusText,
      fetchData,
      handleSearch,
      handleReset,
      handleSortChange,
      goToProductDetail,
      getExportParams,
      formatPrice
    };
  }
};
</script>

<style scoped>
.inventory-status-report {
  margin-top: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.summary-cards {
  margin-bottom: 20px;
}

.summary-card {
  transition: all 0.3s;
}

.summary-card:hover {
  transform: translateY(-5px);
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.summary-icon .el-icon {
  font-size: 24px;
  color: white;
}

.normal-icon {
  background-color: #409EFF;
}

.warning-icon {
  background-color: #E6A23C;
}

.danger-icon {
  background-color: #F56C6C;
}

.info-icon {
  background-color: #909399;
}

.summary-content {
  flex: 1;
}

.summary-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.threshold {
  font-weight: bold;
}

@media print {
  .filter-container {
    display: none !important;
  }
}
</style> 